﻿using UnityEngine;
using System.Collections;
using System;
using YunvaIM;
using UnityEngine.UI;


public class VoiceChatMnager : MonoBehaviour
{
	private long sUserId {
		get { 
			return info.UserInfo.UserData.id;
		}
	}

	private string sUserName {
		get { 
			return info.UserInfo.UserData.nickName;
		}
	}

	private string recordSavePath = string.Empty;
//返回录音地址
	private string localRecordUrlPath = string.Empty;
//返回录音url地址

	public VoiceChatVolumeShower VoiceChatShower;
	public Button VoiceChatBtn;
	/// <summary>
	/// 呀呀语音SDK appid
	/// </summary>
	private uint YYAppId = 1000873;

	/// <summary>
	/// 是不是调试（测试）？
	/// </summary>
	private bool IsDebug {
		get { 
			return Debug.isDebugBuild ? true : false;
		}
	}

	private static bool isInited = false;
	private int voiceTime = 0;

	public static VoiceChatMnager Instance = null;

	void Start ()
	{
		//#if !UNITY_EDITOR && !UNITY_STANDALONE
		if(Instance==null){
			Instance = this;
		}
        EventListenerManager.AddListener(ProtocolEnum.IM_RECORD_VOLUME_NOTIFY, ImRecordVolume);//录音音量大小回调监听
		EventTriggerListener.Get (VoiceChatBtn.gameObject).onDown = OnVoiceBtnPressDown;
		EventTriggerListener.Get (VoiceChatBtn.gameObject).onUp = OnVoiceBtnUp;

		YYSDK_Init ();
		//#endif
	}

	private void OnVoiceBtnPressDown (GameObject go)
	{
		SoundPlayer.play ("7571");
		transform.localPosition = Vector3.zero;
		//Global.IsPlayerDoingYayaVoiceChat = true;
		VoiceChatShower.SetVoiceChatVolumeShower (true);
		YYSDK_StartRecordVoice (sUserId);
	}

	private void OnVoiceBtnUp (GameObject go)
	{
		SoundPlayer.play ("7571");
		//Global.IsPlayerDoingYayaVoiceChat = false;
		VoiceChatShower.SetVoiceChatVolumeShower (false);
		YYSDK_StopRecordVoice ();
	}

	private void YYSDK_Init ()
	{
		if (isInited) {
			VoiceChatBtn.gameObject.SetActive (true);
			return;
		}
		int init = YunVaImSDK.instance.YunVa_Init (0, YYAppId, Application.persistentDataPath, IsDebug);
		if (init == 0) {
			Debug.Log ("初始化成功...");
			//playerName 与userId会知道闪退
			YYSDK_Login (sUserName, sUserId);
			isInited = true;
		} else {
			Debug.Log ("初始化失败...");
		}
	}
		
	/*******************************************************/
	public void YYSDK_Login (string playerName, long playerId)
	{
		Debug.Log ("开始登陆~");
		string ttFormat = "{{\"nickname\":\"{0}\",\"uid\":\"{1}\"}}";
		string tt = string.Format (ttFormat, playerName, playerId);
		string[] wildcard = new string[2];
		wildcard [0] = playerName;
		wildcard [1] = playerId.ToString();
		YunVaImSDK.instance.YunVaOnLogin (tt, "jjmjserver01", wildcard, 0, (data) => {
			Debug.Log("data.result:"+data.result);
			if (data.result == 0) {
				Debug.Log(string.Format("登录成功，昵称:{0},用户ID:{1}", data.nickName, data.userId));
				YunVaImSDK.instance.RecordSetInfoReq (true);//开启录音的音量大小回调
			} else {
				Debug.Log(string.Format ("登录失败，错误消息：{0}", data.msg));
			}
			VoiceChatBtn.gameObject.SetActive (true);
		});
	}

	public void YYSDK_Logout ()
	{
		YunVaImSDK.instance.YunVaLogOut ();
	}

	/// <summary>
	/// 开始录音
	/// </summary>
	public void YYSDK_StartRecordVoice (long playerId)
	{
		recordSavePath = string.Format ("{0}/{1}.amr", Application.persistentDataPath, playerId);
		YunVaImSDK.instance.RecordStartRequest (recordSavePath);
	}

	/// <summary>
	/// 停止录音
	/// </summary>
	public void YYSDK_StopRecordVoice ()
	{
		YunVaImSDK.instance.RecordStopRequest (OnGotStopRecordResponseCallBack);
	}



	public void YYSDK_StopPlayRecordVoice ()
	{
		Debug.Log ("停止播放");
		YunVaImSDK.instance.RecordStopPlayRequest ();
	}

	/// <summary>
	/// 上传语音
	/// </summary>
	public void YYSDK_UploadVoice (long playerId)
	{
		Debug.Log ("准备上传：" + recordSavePath);
		YunVaImSDK.instance.UploadFileRequest (recordSavePath, playerId.ToString (), (data1) => {
			if (data1.result == 0) {
				localRecordUrlPath = data1.fileurl;
				Debug.Log ("上传成功:" + localRecordUrlPath);
				//通知其他的玩家去下载该语音，然后进行播放
				Debug.Log("data1.fileurl:"+data1.fileurl);
				GSocket.Send(tools.ByteFactory.makeByte(102102,data1.fileurl));
			} else {
				Debug.Log ("上传失败:" + data1.msg);
			}
		});
	}

	/// <summary>
	/// 播放录音，
	/// </summary>
	public void YYSDK_PlayRecordVoice (long playerId)
	{
		recordSavePath = string.Format ("{0}/{1}.amr", Application.persistentDataPath, playerId);

		YunVaImSDK.instance.RecordStartPlayRequest (recordSavePath, "", "", (data2) => {
			if (data2.result == 0) {
				Debug.Log ("播放成功");	
				new tools.cashDataLoader().RemoveVoice(playerId.ToString());
			} else {
				Debug.Log ("播放失败");
			}
		});
	}

	/// <summary>
	/// 下载对应fileId的语音
	/// </summary>
	/// <param name="fileId">File identifier.</param>
	public void YYSDK_DownloadVoice (string remoteVoiceUrl, long playerId, Action<bool> downloadedCallback)
	{
		string DownLoadfilePath = string.Format ("{0}/{1}.amr", Application.persistentDataPath, playerId);
		Debug.Log ("下载语音:" + DownLoadfilePath);
		YunVaImSDK.instance.DownLoadFileRequest (remoteVoiceUrl, DownLoadfilePath, playerId.ToString (), (data4) => {
			if (data4.result == 0) {
				Debug.Log ("下载成功:" + data4.filename);
				//下载成功进行语音的播放
				if (downloadedCallback != null) {
					downloadedCallback (true);
				}
			} else {
				Debug.Log ("下载失败:" + data4.msg);
				if (downloadedCallback != null) {
					downloadedCallback (false);
				}
			}
		});
	}

	/// <summary>
	/// 录音停止回调事件
	/// </summary>
	/// <param name="data">Data.</param>
	private void  OnGotStopRecordResponseCallBack (ImRecordStopResp  data)
	{
		if (!string.IsNullOrEmpty (data.strfilepath)) {
			recordSavePath = data.strfilepath;
			VoiceChatShower.SetVoiceChatVolumeShower (false);
			voiceTime = (int)data.time / 1000;//毫秒
			if (voiceTime < 1) {
				return;
			}
			YYSDK_UploadVoice (sUserId);
		}
	}

	/// <summary>
	///  录音过程中，音量大小变化
	/// </summary>
	/// <param name="data">Data.</param>
	public void ImRecordVolume (object data)
	{
		ImRecordVolumeNotify RecordVolumeNotify = data as ImRecordVolumeNotify;
		int level = GetVolumeLevel (RecordVolumeNotify.v_volume);
		DisplayVolumeUI (level);
	}


	public void DisplayVolumeUI (int level)
	{
		VoiceChatShower.SetVolume (level);
	}

	/// <summary>
	/// 0-4
	/// </summary>
	/// <returns>The volume level.</returns>
	/// <param name="v_volume">V volume.</param>
	public int GetVolumeLevel (int v_volume)
	{
		float templevel = (v_volume / 25.0f);
		return (int)Math.Ceiling (templevel);
	}

	void OnApplicationQuit ()
	{
		YYSDK_Logout ();
		isInited = false;
		Instance = null;
	}
   
}
